/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	owner.HTTP = 'http://www.tech-zone.cn:1505/' //'http://192.168.0.16:1505/' 'http://www.tech-zone.cn:1505/';
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		plus.nativeUI.showWaiting('登录中', {
			width: '100px',
			height: '100px'
		});
		callback = callback || $.noop;
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';

		var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
		if (loginInfo.account.length < 11) {
			return callback('用户名最短需要 11 个位');
		} else {
			if (!myreg.test(loginInfo.account)) {
				return callback('手机号格式有误！');
			}
		}
		if (loginInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}

		var info = plus.push.getClientInfo();
		console.log("手机唯一识别CID：" + info.clientid || loginInfo.userCID)
		var userData = {}
		mui.post(owner.HTTP + 'api/Users/Login', {
			userName: loginInfo.account,
			userPwd: loginInfo.password,
			userCID: info.clientid || loginInfo.userCID
		}, function(res) {
			plus.nativeUI.closeWaiting();
			if (res.code == 1001) {
				userData.userID = res.data.userID; // 用户ID
				userData.stand = res.data.stand; // 用户等级身份
				userData.neiID = res.data.neiID // 小区ID
				userData.account = loginInfo.account; // 用户账号
				userData.password = loginInfo.password; // 用户密码
				userData.userCID = info.clientid; // 手机唯一识别码 
				return owner.createState(userData)
			} else {
				return callback(res.message)
			}
		})
	};

	owner.createState = function(data) {
		var state = owner.getState();
		state.userID = data.userID;
		state.account = data.account;
		state.password = data.password;
		owner.setState(state);
		console.log('用户身份：' + data.stand)
		console.log("用户userID：" + state.userID)
		console.log("小区ID：" + data.neiID)
		if (data.stand == -1) { // 账号身份 注：返回 4正式业主 5临时业主 -1代表未认证
			owner.onPerfectUser()
		} else {
			if (data.stand < 4) {
				plus.nativeUI.confirm('系统检测出你的账号在员工端已被注册，无法登陆成功请联系客服人员', function(e) {
					if (e.index == 1) {
						plus.device.dial('10086', false);
					}
				}, {
					buttons: ['取消', '立即联系']
				})
				return
			}
			owner.neiID(data.neiID)
			owner.onHome()
		}
	};

	owner.onHome = function() { // 跳转值 index 首页
		mui.openWindow({
			url: 'index.html',
			id: 'index',
			show: {
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		})
	}

	owner.onPerfectUser = function() { // 跳转值 完善业主信息页面
		mui.toast('请完善您的业主信息')
		mui.openWindow({
			url: 'register/perfectUser.html',
			id: 'perfectUser',
			styles: { // 窗口参数 参考5+规范中的WebviewStyle,也就是说WebviewStyle下的参数都可以在此设置
				titleNView: { // 窗口的标题栏控件
					titleText: "完善业主信息", // 标题栏文字,当不设置此属性时，默认加载当前页面的标题，并自动更新页面的标题         // 字体颜色,颜色值格式为"#RRGGBB",默认值为"#000000"
					titleSize: "17px", // 字体大小,默认17px
					backgroundColor: "#ffffff", // 控件背景颜色,颜色值格式为"#RRGGBB",默认值为"#F7F7F7"
					splitLine: { // 标题栏控件的底部分割线，类似borderBottom
						color: "#eeeeee", // 分割线颜色,默认值为"#CCCCCC"  
						height: "1px" // 分割线高度,默认值为"2px"
					}
				}
			},
			show: {
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		})
	}

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account.toString()
		regInfo.password = regInfo.password || '';
		var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
		if (regInfo.account.length < 11) {
			return callback('用户名最短需要 11 个位');
		} else {
			if (!myreg.test(regInfo.account)) {
				return callback('手机号格式有误！');
			}
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}

		//		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		//		users.push(regInfo);
		//		localStorage.setItem('$users', JSON.stringify(users));
		mui.post(owner.HTTP + 'api/Users/RegisterUser', {
			userName: regInfo.account,
			userPwd: regInfo.password
		}, function(res) {
			if (res.code == 1001) {
				return callback();
			} else {
				return callback(res.message)
			}
		})
	};
	owner.neiID = function(data) {
			plus.storage.setItem('neiID', JSON.stringify({
				neiID: data
			}))
		},
		/**
		 * 获取当前状态
		 **/
		owner.getState = function() {
			var stateText = plus.storage.getItem('$state') || "{}";
			return JSON.parse(stateText);
		};
	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		plus.storage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.Password = function(data, callback) {
		callback = callback || $.noop;
		data = data || {};
		data.ipone = data.ipone.toString()
		data.passwords = data.passwords || '';
		var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
		if (data.ipone.length < 11) {
			return callback('用户名最短需要 11 个位');
		} else {
			if (!myreg.test(data.ipone)) {
				return callback('手机号格式有误！');
			}
		}
		if (regInfo.passwords.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		callback()
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		plus.storage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = plus.storage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}

	/**
	 * 设置用户完善信息状态
	 */
	owner.setUserState = function(state) {
		plus.storage.setItem('$userState', JSON.stringify(state))
	}

	/*
	 * 获取a用户完善信息状态
	 */
	owner.getUserState = function() {
		var userState = plus.storage.getItem('$userState')
		return JSON.parse(userState)
	}


	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(mui, window.app = {}));
